package com.lexue.articlesync.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 简单的图片托管服务
 * 将本地图片复制到可通过HTTP访问的静态资源目录
 */
@Slf4j
@Service
public class ImageHostingService {

    @Value("${server.port:8081}")
    private int serverPort;

    // 静态资源目录
    private static final String STATIC_IMAGES_DIR = "src/main/resources/static/images/uploads";
    // Web访问路径
    private static final String WEB_IMAGES_PATH = "/images/uploads";

    /**
     * 上传本地图片到可访问的位置
     * @param localImagePath 本地图片路径
     * @return 可访问的HTTP URL，失败返回null
     */
    public String hostLocalImage(String localImagePath) {
        try {
            File sourceFile = new File(localImagePath);
            if (!sourceFile.exists()) {
                log.error("本地图片文件不存在: {}", localImagePath);
                return null;
            }

            // 创建目标目录
            Path targetDir = Paths.get(STATIC_IMAGES_DIR);
            if (!Files.exists(targetDir)) {
                Files.createDirectories(targetDir);
            }

            // 生成唯一文件名
            String originalFileName = sourceFile.getName();
            String extension = getFileExtension(originalFileName);
            String uniqueFileName = UUID.randomUUID().toString() + "." + extension;
            
            // 复制文件到静态资源目录
            Path targetPath = targetDir.resolve(uniqueFileName);
            Files.copy(sourceFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            // 构建可访问的HTTP URL
            String httpUrl = String.format("http://localhost:%d%s/%s", 
                    serverPort, WEB_IMAGES_PATH, uniqueFileName);
            
            log.info("本地图片已托管: {} -> {}", localImagePath, httpUrl);
            return httpUrl;
            
        } catch (IOException e) {
            log.error("托管本地图片失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex + 1).toLowerCase();
        }
        return "jpg"; // 默认扩展名
    }

    /**
     * 清理过期的托管图片
     */
    public void cleanupExpiredImages() {
        try {
            Path imagesDir = Paths.get(STATIC_IMAGES_DIR);
            if (!Files.exists(imagesDir)) {
                return;
            }

            long currentTime = System.currentTimeMillis();
            long oneHourAgo = currentTime - (60 * 60 * 1000); // 1小时前

            Files.list(imagesDir)
                    .filter(Files::isRegularFile)
                    .forEach(file -> {
                        try {
                            long lastModified = Files.getLastModifiedTime(file).toMillis();
                            if (lastModified < oneHourAgo) {
                                Files.delete(file);
                                log.debug("删除过期托管图片: {}", file.getFileName());
                            }
                        } catch (IOException e) {
                            log.warn("删除过期图片失败: {}", e.getMessage());
                        }
                    });

        } catch (IOException e) {
            log.error("清理过期图片失败: {}", e.getMessage());
        }
    }
}